import { Button, Form, Input, Modal, Space, Table } from "antd";
import styles from "./Password.module.css";
import React, { useEffect, useState } from "react";
import TextArea from "antd/es/input/TextArea";
import { passwordApi } from "../../../../utils/backend/server";
import { toast } from "../../../../components/Toast/Toast";
import { Login } from "../../../../components/LoginAndRegister/Login/Login";
import { updateForm as updateInput } from "../../../../utils/utils/setInput";
// import { Register } from "../../../../components/Register/Register";
import { copyText } from "../../../../utils/common/copy";
import { AxiosError, AxiosResponse } from "axios";
import {
  PasswordPair,
  PasswordWithType,
} from "../../../../utils/domain/keyword";
import { useAppDispatch } from "../../../../utils/store/hooks";
import {
  updateLogin,
  updateRegister,
} from "../../../../utils/store/deviceSlice";
import { PasswordType } from "../../../Password/Password";

// export type PasswordPair = {
//   id?: string | number;
//   account: string;
//   password: string;
// };

export type OptionalPasswordType = Partial<PasswordType>;

export type EditorType = PasswordType & { show: boolean; isEdit: boolean };

export type WithPass = {
  id?: string | number;
  account: string;
  password: string;
  memo: string;
  type: "password" | "text";
};

// type EditorTypeWithPass = EditorType & {  };
export interface EditorInterface extends EditorType {
  pair: WithPass[];
}
export const converter: (data: EditorType) => EditorInterface = (data) => ({
  ...data,
  pair: data.pair.map((val) => ({ ...val, type: "password" })),
});

const handleLoginError = (error: AxiosError) => {
  if (error.response?.status === 400) {
    toast("please login first!");
    throw Error("handled error!");
  }
  const msg = (error as any).data.msg;
  console.log(error, "err");
  toast(msg);
};

export const Editor = (props: { data: EditorType; reload: () => void }) => {
  const [form, setForm] = useState<EditorInterface>(converter(props.data));

  useEffect(() => {
    setForm(converter(props.data));
  }, [props.data]);

  const check = (data: PasswordType) => {
    // if (data.url === "") {
    //   toast("please check url");
    //   return false;
    // }
    const item = data.pair.find(
      (val) => val.account === "" || val.password === ""
    );
    if (item) {
      toast(`please check ${item.account === "" ? "account" : "password"}`);
      return false;
    }
    return true;
  };
  // const handleOk = async () => {
  //   if (!check(form)) return;
  //   try {
  //     await passwordApi[
  //       props.data.isEdit ? "updatePassword" : "createPassword"
  //     ]('',form);
  //     props.reload();
  //     handleCancel();
  //   } catch (error) {
  //     handleLoginError(error as AxiosError);
  //   }
  // };
  const handleCancel = () => {
    setForm({
      show: false,
      // url: "",
      pair: [
        {
          account: "",
          password: "",
          memo: "",
          type: "password",
        },
      ],
      memo: "",
      isEdit: false,
    });
  };

  const addPair = () => {
    setForm((e) => ({
      ...e,
      pair: [
        ...e.pair,
        {
          password: "",
          account: "",
          memo: "",
          type: "password",
        },
      ],
    }));
  };

  const updateForm = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => updateInput(e, setForm);

  const removePair = (index: number) => {
    if (form.pair.length === 1) return toast("at least leave one pair!");
    setForm((e) => ({
      ...e,
      pair: (e.pair as unknown as WithPass[]).filter(
        (val, seq: number) => seq !== index
      ),
    }));
  };

  const visibility = (type: "password" | "text", index: number) => {
    setForm((val) => ({
      ...val,
      pair: val.pair.map((e, seq) => ({
        ...e,
        type: seq === index ? type : e.type,
      })),
    }));
  };
  const copy = async (id: number | string) => {
    const res = await passwordApi.retrievePassword(id);
    if (!res.success) {
      toast(res.msg);
      return;
    }
    copyText(res.data.password);
    toast("copied!");
    console.log(res.data.password);
  };
  return (
    <Modal
      open={form.show}
      onCancel={handleCancel}
      title={form.isEdit ? "edit" : "add"}
      destroyOnClose
      footer={
        <Space>
          <Button danger onClick={addPair}>
            add
          </Button>
          <Button
            type="primary"
            onClick={() => {
              //handleOk
            }}
          >
            confirm
          </Button>
        </Space>
      }
    >
      <Form
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={() => {}}
        onFinishFailed={() => {}}
        autoComplete="off"
      >
        {/* <Form.Item<OptionalPasswordType>
          label="url"
          name="url"
          rules={[{ required: true, message: "Please input your url!" }]}
          initialValue={props.data.url}
        >
          <Input value={form.url} name="url" onChange={updateForm} />
        </Form.Item> */}

        <div className={styles.pair}>
          {form.pair.map((val, index) => (
            <div key={"pair" + index}>
              <Form.Item<OptionalPasswordType>
                label="account"
                rules={[
                  { required: true, message: "Please input your account!" },
                ]}
                initialValue={val.account}
              >
                <Space.Compact style={{ width: "100%" }}>
                  <Input
                    value={val.account}
                    name={`['pair']['${index}']['account']`}
                    onChange={updateForm}
                  />
                  <Button
                    type="primary"
                    danger
                    onClick={() => removePair(index)}
                  >
                    -
                  </Button>
                </Space.Compact>
              </Form.Item>
              <Form.Item<OptionalPasswordType>
                label="password"
                rules={[
                  { required: true, message: "Please input your password!" },
                ]}
                initialValue={val.password}
              >
                <Space.Compact style={{ width: "100%" }}>
                  <Input
                    value={val.password}
                    name={`['pair']['${index}']['password']`}
                    onChange={updateForm}
                    type={val.type}
                  />
                  {form.isEdit ? (
                    <Button
                      type="primary"
                      onClick={() => {
                        copy(val.id || "");
                      }}
                    >
                      copy
                    </Button>
                  ) : (
                    <>
                      <Button
                        type="primary"
                        onClick={() =>
                          visibility(
                            val.type === "password" ? "text" : "password",
                            index
                          )
                        }
                      >
                        {val.type === "password" ? "show" : "hide"}
                      </Button>
                      {form.pair.length - 1 === index ? (
                        <Button type="primary" onClick={addPair}>
                          +
                        </Button>
                      ) : (
                        <></>
                      )}
                    </>
                  )}
                </Space.Compact>
              </Form.Item>
            </div>
          ))}
        </div>
        {/* <Form.Item<OptionalPasswordType>
          label="memo"
          name="memo"
          rules={[{ required: false, message: "Please input your memo!" }]}
          initialValue={form.memo}
        >
          <TextArea
            rows={3}
            value={form.memo}
            name="memo"
            onChange={updateForm}
          />
        </Form.Item> */}
      </Form>
    </Modal>
  );
};

export const Password = () => {
  const [chosen, setChosen] = useState<EditorType>({
    show: false,
    // url: "",
    pair: [],
    memo: "",
    isEdit: false,
  });
  const [keyword, setKeyword] = useState<string>("");
  const [list, setList] = useState<PasswordType[]>();

  const dispatch = useAppDispatch();

  // const [showLogin, setShowLogin] = useState<boolean>(false);
  // const [showRegister, setShowRegister] = useState<boolean>(false);
  // const dataSource = [
  //   {
  //     key: "1",
  //     url: "www.baidu.com",
  //     pair: [
  //       {
  //         account: "abcdef",
  //         password: "10 Downing Street",
  //       },
  //     ],
  //     memo: "",
  //   },
  // ];
  useEffect(() => {
    reload();
  }, []);

  const reload = () => {
    passwordApi.getAllPasswords(keyword).then((res) => {
      console.log(res);
      setList(res.data);
      toast(res.msg);
    });
  };
  const columns = [
    {
      title: "website",
      dataIndex: "url",
      key: "url",
    },
    {
      title: "memo",
      dataIndex: "memo",
      key: "memo",
    },
    {
      title: "operation",
      dataIndex: "operation",
      key: "operation",
      render: (_: any, entity: PasswordType, index: number) => {
        const remove = async () => {
          // passwordApi.remove
          if (!entity.id) return toast("id is missing from entity!");
          try {
            await passwordApi.deletePassword(entity.id);
          } catch (error) {
            handleLoginError(error as AxiosError);

            toast("remove failed: " + error);
          } finally {
            reload();
          }
        };
        return (
          <Space>
            <Button danger type="primary" onClick={remove}>
              remove
            </Button>
            <Button
              type="primary"
              onClick={() => {
                setChosen({ ...entity, show: true, isEdit: true });
              }}
            >
              detail
            </Button>
          </Space>
        );
      },
    },
  ];

  return (
    <div className={styles.container}>
      <Table
        dataSource={list}
        columns={columns}
        rowKey={"id"}
        title={() => {
          return (
            <Space>
              <Button type="primary" onClick={reload}>
                reload
              </Button>
              <Button
                type="primary"
                onClick={() => dispatch(updateRegister(true))}
              >
                register
              </Button>
              <Button
                type="primary"
                onClick={() => dispatch(updateLogin(true))}
              >
                login
              </Button>
              <Button
                type="primary"
                onClick={
                  () => {}
                  // setChosen({
                  //   url: "https://",
                  //   pair: [{ password: "", account: "" }],
                  //   memo: "",
                  //   show: true,
                  //   isEdit: false,
                  // })
                }
              >
                add
              </Button>
              <Input
                value={keyword}
                onChange={(e) => setKeyword(e.target.value)}
                onPressEnter={reload}
              />
            </Space>
          );
        }}
        bordered
        scroll={{ x: 1000, y: 1000 }}
        virtual
      />

      <Editor data={chosen} reload={reload} />
      {/* <Login show={showLogin} close={() => setShowLogin(false)} />
      <Register show={showRegister} close={() => setShowRegister(false)} /> */}
    </div>
  );
};
